package com.my.library.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.my.library.auth.CustomInvocationSecurityMetadataSourceService;
import com.my.library.entity.User;

public class AuthFilter implements Filter {
	
	CustomInvocationSecurityMetadataSourceService service = new CustomInvocationSecurityMetadataSourceService();
	
	public void init(FilterConfig fConfig) throws ServletException {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse res = (HttpServletResponse)response;
		res.setContentType("text/html;charset=UTF-8");
		
		// 登录拦截
		HttpServletRequest req = (HttpServletRequest)request;
		String url = req.getRequestURI();
		
		System.out.println("queryString: " + req.getQueryString());
		
		System.out.println("url: " + req.getRequestURL());
		if(url.contains("login") || url.contains("/js/")) {
			chain.doFilter(request, response);
			return;
		}
		HttpSession session = req.getSession();
		User u = (User) session.getAttribute("user");
		if(u == null) {
			PrintWriter writer = response.getWriter();
			writer.println("<a href='" + req.getServletContext().getContextPath() + "/login.jsp?dest=" + req.getRequestURL() + "?" + req.getQueryString() + "'>请登录</a>");
			return;
		} else {
			String path = req.getContextPath();
			url = url.substring(path.length());
			System.out.println("request url: " + url);
			if(service.verify(url, u)) {
				chain.doFilter(request, response);
				return;
			} else {
				PrintWriter writer = response.getWriter();
				writer.println("对不起,您没有该权限!");
				return;
			}
		}
		
	}
	
	public void destroy() {
		// TODO Auto-generated method stub
	}
	
	public static void main(String[] args) {
		
	}

}
